import { reqUserLogin, reqUserLogout } from '@/api'
import { Message } from 'element-ui'
const state = {
  user: {
    name: localStorage.getItem('userName'),
    token: localStorage.getItem('userToken'),
  },
}
const actions = {
  //用户登录请求
  async getUserInfo({ commit }, user) {
    const result = await reqUserLogin(user)
    if (result.code === 200) {
      Message.success('登录成功！')
      localStorage.setItem('userName', result.data.name)
      localStorage.setItem('userToken', result.data.token)
      commit('SAVE_USER_INFO', result.data)
    } else {
      console.log(result.message)
    }
  },

  //用户退出登录请求
  async userLogout({ commit }) {
    const result = await reqUserLogout()
    if (result.code === 200) {
      localStorage.removeItem('userName')
      localStorage.removeItem('userToken')
      commit('USER_LOGOUT')
      Message.success('退出登录成功！')
    } else {
      console.log(result.message)
    }
  },
}
const mutations = {
  SAVE_USER_INFO(state, payload) {
    state.user.name = payload.name
    state.user.token = payload.token
  },
  USER_LOGOUT(state) {
    state.user.name = ''
    state.user.token = ''
  },
}

const getters = {}

export default {
  namespaced: true,
  state,
  mutations,
  actions,
  getters,
}
